package com.example.objectstoragejava.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping(value = "normal")
public class NormalUpload {

    List<HashMap> partList = new ArrayList<>();

    @PostMapping(value = "upload")
    public Boolean upload(@RequestParam(value = "file") MultipartFile file,
                          @RequestParam(value = "chunk", required = false) Integer chunk,
                          @RequestParam(value = "chunks", required = false) Integer chunks,
                          @RequestParam(value = "uploadId", required = false) String uploadId,
                          @RequestParam(value = "fileName", required = false) String fileName)
            throws IOException {
        if (uploadId == null) {
            log.info("fileName {}", fileName);
            return true;
        }
        // 模拟数据，采用stream存储到内存
        var map = new HashMap<String, Object>();
        map.put("file", file.getInputStream());
        map.put("chunk", chunk);
        map.put("chunks", chunks);
        map.put("uploadId", uploadId);
        partList.add(map);
        return true;
    }

    @GetMapping(value = "merge")
    public Boolean merge(@RequestParam("uploadId") String uploadId, @RequestParam("fileName") String fileName) throws IOException {
        var uploadIdList = partList.stream().filter((item) -> item.get("uploadId")
                        .equals(uploadId))
                .sorted(Comparator.comparing((item) -> (Integer) item.get("chunk")))
                .toList();
        var file = new FileOutputStream("D:\\" + fileName);
        uploadIdList.forEach((item) -> {
            try {
                var inputStream = (InputStream) item.get("file");
                file.write(inputStream.readAllBytes());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        file.flush();
        file.close();
        return true;
    }
}
